<template>
  <div class="accidentPreivewNewReport" v-loading="isLoading">
    <ty-breadcrumb />
    <div class="ty-container ty-detail">
      <div class="ty-bar">
        <div class="ty-headline">事故上报</div>
        <div>
          <template v-if="editFlag">
            <!-- editFlag: true 可编辑  false： 不可编辑  -->
            <el-button type="primary" @click="submitForm('report')">上报</el-button>
            <el-button type="primary" @click="submitForm('save')">保存</el-button>
            <el-button @click="cancle">取消</el-button>
          </template>
          <template v-else>
            <el-button @click="cancle">返回</el-button>
          </template>
        </div>
      </div>
      <div class="ty-content">
        <el-form>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="事故编码：">
                {{ accidentForm.code }}
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="事故标题：">
                {{ accidentForm.name }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="事发时间：">
                {{ accidentForm.startTime }}
                <el-button
                  type="text"
                  icon="el-icon-edit-outline"
                  style="color: #00A0B8 ;"
                  @click="updateAccidentForm('startTime', 'date', '事发时间')"
                  v-if="editFlag"
                ></el-button>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="事故地点：">
                {{ accidentForm.place }}
                <el-button
                  type="text"
                  icon="el-icon-edit-outline"
                  style="color: #00A0B8 ;"
                  @click="updateAccidentForm('place', 'text', '事故地点')"
                  v-if="editFlag"
                ></el-button>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="事故类型：">
                {{ accidentForm.accidentType | formatDict(accidentTypeDict) }}
                <el-button
                  type="text"
                  icon="el-icon-edit-outline"
                  style="color: #00A0B8 ;"
                  @click="updateAccidentForm('accidentType', 'select', '事故类型')"
                  v-if="editFlag"
                ></el-button>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="事故等级：">
                {{ accidentForm.level | formatDict(levelDictList) }}
                <el-button
                  type="text"
                  icon="el-icon-edit-outline"
                  style="color: #00A0B8 ;"
                  @click="updateAccidentForm('level', 'select', '事故等级')"
                  v-if="editFlag"
                ></el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="事故危险物质：">
                {{ accidentForm.dangerous | formatDangerous(dangerousDictList) }}
                <el-button
                  type="text"
                  icon="el-icon-edit-outline"
                  style="color: #00A0B8 ;"
                  @click="updateAccidentForm('dangerousList', 'select', '事故危险物质')"
                  v-if="editFlag"
                ></el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="事故描述：">
                {{ accidentForm.description }}
                <el-button
                  type="text"
                  icon="el-icon-edit-outline"
                  style="color: #00A0B8 ;"
                  @click="updateAccidentForm('description', 'textarea', '事故描述')"
                  v-if="editFlag"
                ></el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="人员伤亡：">
                {{ accidentForm.deathNum }}
                <el-button
                  type="text"
                  icon="el-icon-edit-outline"
                  style="color: #00A0B8 ;"
                  @click="updateAccidentForm('deathNum', 'num', '人员伤亡')"
                  v-if="editFlag"
                ></el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注：">
                {{ accidentForm.remark }}
                <el-button
                  type="text"
                  icon="el-icon-edit-outline"
                  style="color: #00A0B8 ;"
                  @click="updateAccidentForm('remark', 'textarea', '备注')"
                  v-if="editFlag"
                ></el-button>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报送部门：">
                {{ accidentForm.subDept }}
                <el-button
                  type="text"
                  icon="el-icon-edit-outline"
                  style="color: #00A0B8 ;"
                  @click="updateAccidentForm('subDept', 'text', '报送部门')"
                  v-if="editFlag"
                ></el-button>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报送人：">
                {{ accidentForm.subPersonName }}
                <!--                <el-button type="text" icon="el-icon-edit-outline" style="color: #00A0B8 ;" @click="updateAccidentForm('subPerson', 'text', '报送人')" v-if="editFlag"></el-button>-->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报送时间：">
                {{ accidentForm.subTime }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="附件：">
                {{ accidentForm.attachmentName }}
                <el-button
                  type="text"
                  icon="el-icon-edit-outline"
                  style="color: #00A0B8 ;"
                  @click="updateAccidentForm('fileList', 'file', '附件')"
                  v-if="editFlag"
                ></el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <el-dialog :title="dialogTitle" :visible="dialogVisible" append-to-body width="600px">
      <el-form>
        <template v-if="dialogType === 'date'">
          <el-date-picker
            v-model="dialogValue"
            type="datetime"
            placeholder="选择日期"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions"
            style="width: 100%;"
          ></el-date-picker>
        </template>
        <template v-if="dialogType === 'text'">
          <el-input v-model="dialogValue" :placeholder="`请输入${dialogTitle}`" />
        </template>
        <template v-if="dialogType === 'num'">
          <el-input-number v-model="dialogValue" :max="999999" :min="0" placeholder="请输入人员伤亡" />
        </template>
        <template v-if="dialogType === 'textarea'">
          <el-input
            v-model="dialogValue"
            :label="dialogTitle"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 4 }"
            resize="none"
            clearable
            maxlength="1000"
            show-word-limit
            :placeholder="`请输入${dialogTitle}`"
          ></el-input>
        </template>
        <template v-if="dialogType === 'select'">
          <el-select
            v-model="dialogValue"
            label="事故类型"
            :clearable="dialogKey === 'level' ? false : true"
            :multiple="dialogKey === 'dangerousList'"
            filterable
          >
            <el-option
              v-for="item in dialogDict"
              :key="dialogKey === 'dangerousList' ? item.id : item.value"
              :label="dialogKey === 'dangerousList' ? item.sdsName : item.label"
              :value="dialogKey === 'dangerousList' ? item.id : item.value"
            ></el-option>
          </el-select>
        </template>
        <template v-if="dialogType === 'file'">
          <ty-upload v-model="fileList" label="附件" name="files" :limit="1" :editable="true" :size="50">
            <el-button size="small" icon="el-icon-upload">选择文件</el-button>
            <span slot="tip" class="el-upload__tip" style="display: inline-block; margin-left: 10px">
              (文件大小不超过 50M)
            </span>
          </ty-upload>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCancle">取 消</el-button>
        <el-button type="primary" @click="dialogSave">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions, mapState } from "vuex"
import cloneDeep from "lodash/cloneDeep"
let formatDates = () => {}
let api = {}
export default {
  name: "AccidentPreivewReport",
  data() {
    return {
      accidentForm: {},
      fileList: [],
      dialogVisible: false,
      dialogValue: "",
      dialogTitle: "",
      dialogKey: "",
      dialogDict: [],
      dialogType: "",
      editFlag: true, // 编辑按钮控制
      routerPageType: "",
      levelDictList: [
        { label: "一般事故(IV级)", value: 4 },
        { label: "较大事故(III级)", value: 3 },
        { label: "重大事故(II级)", value: 2 },
        { label: "特别重大事故(I级)", value: 1 },
      ],
      // 时间限制  禁止选择之后的时间
      pickerOptions: {
        disabledDate: function(time) {
          return time.getTime() > Date.now()
        },
      },
      isLoading: false,
    }
  },
  computed: {
    ...mapState({
      accidentFormInfo: state => state.accidentReport.accidentForm,
      accidentTypeDict: state => state.accidentNew.accidentTypeDict,
      dangerousDictList: state => state.accidentReport.dangerousDictList,
    }),
  },
  async created() {
    if (!(this.dangerousDictList && this.dangerousDictList.length > 0)) {
      this.isLoading = true
      await this.getSdsData()
      this.isLoading = false
    }
    let accidentId = this.$router?.history?.current?.query?.id
    this.routerPageType = this.$router?.history?.current?.query?.pageType
    // 预览状态
    if (accidentId) {
      this.editFlag = false
      this.getAccidentInfo(accidentId)
      return
    }
    this.editFlag = true
    if (!this.accidentFormInfo || JSON.stringify(this.accidentFormInfo) === "{}") {
      this.$router.push({ path: "/zw-others/accidentReport" })
      return
    }
    this.accidentForm = cloneDeep({
      ...this.accidentFormInfo,
      level: this.accidentFormInfo?.level ? this.accidentFormInfo.level : 4,
    })
    this.fileList =
      this.accidentForm.attachmentId && this.accidentForm.attachmentName
        ? [{ id: this.accidentForm.attachmentId, name: this.accidentForm.attachmentName }]
        : []
    if (!this.accidentForm.code) this.getGenerateCode()
    this.accidentForm.dangerousList =
      this.accidentForm.dangerous && this.accidentForm.dangerous.constructor !== Array
        ? this.accidentForm.dangerous?.split(",")
        : []
    this.accidentForm.subTime = formatDates(new Date(), "yyyy-MM-dd hh:mm:ss")
  },
  methods: {
    ...mapActions(["getSdsData"]),
    // 查看时
    getAccidentInfo(id) {
      this.isLoading = true
      api
        .infoAccident(id)
        .then(res => {
          this.accidentForm = cloneDeep({
            ...res,
            dangerousList: res.dangerous?.split(","),
          })
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 生成事故编码
    getGenerateCode() {
      api.accidentGenerateCode({ startTime: this.accidentForm.startTime }).then(data => {
        this.accidentForm.code = data || ""
      })
    },
    // 修改单个值
    updateAccidentForm(key, type, name) {
      this.dialogVisible = true
      this.dialogValue = this.accidentForm[key]
      this.dialogKey = key
      this.dialogType = type
      this.dialogTitle = name
      if (key === "fileList") {
        this.fileList =
          this.accidentForm.attachmentId && this.accidentForm.attachmentName
            ? [{ id: this.accidentForm.attachmentId, name: this.accidentForm.attachmentName }]
            : []
      }
      let dict = {
        accidentType: this.accidentTypeDict,
        level: this.levelDictList,
        dangerousList: this.dangerousDictList,
      }
      this.dialogDict = dict[key] || []
    },
    // 保存修改的值
    dialogSave() {
      if (!this.dialogValue && ["startTime", "place", "accidentType"].includes(this.dialogKey)) {
        this.$message.error(this.dialogTitle + "不能为空")
        return
      }
      if (this.dialogKey === "dangerousList") {
        this.accidentForm.dangerousList = this.dialogValue
        this.accidentForm.dangerous = this.dialogValue
      } else if (this.dialogKey === "fileList") {
        this.accidentForm.attachmentId = this.fileList?.[0]?.id || ""
        this.accidentForm.attachmentName = this.fileList?.[0]?.name || ""
      } else {
        this.accidentForm[this.dialogKey] = this.dialogValue
      }
      if (this.dialogKey === "deathNum") {
        this.accidentForm.level = Number(this.accidentForm.deathNum) ? 2 : 4
      }
      this.dialogVisible = false
    },
    dialogCancle() {
      this.dialogVisible = false
      if (this.dialogKey === "fileList") {
        this.fileList = []
      }
    },
    submitForm(type) {
      if (type === "save") this.accidentForm.status = "0"
      if (type === "report") this.accidentForm.status = "1"
      if (this.accidentForm?.dangerous && this.accidentForm.dangerous.constructor === Array) {
        this.accidentForm.dangerous = this.accidentForm?.dangerous.join(",")
      }
      this.accidentForm.isDrill = 0
      api.addAccident(this.accidentForm).then(data => {
        this.$message.success(`${type === "save" ? "保存" : "上报"}成功`)
        // this.cancle()
        this.$router.push({ path: "/zw-others/accidentNew" })
      })
    },
    cancle() {
      this.$router.push({
        path: this.routerPageType === "report" ? "/zw-others/accidentReport" : "/zw-others/accidentNew",
      })
      // this.$router.push({ path: "/accidentReport" })
    },
  },
  filters: {
    formatDict(value, dataList = [], placeholder = "-", valueName = "value", labelName = "label") {
      let optionName = placeholder
      dataList.map(val => {
        if (value == val[valueName]) {
          optionName = val[labelName]
        }
      })
      return optionName
    },
    formatDangerous(value, dataList = []) {
      let result = []
      if (value) {
        let list = null
        if (value.constructor === Array) {
          list = value
        } else {
          list = value?.split(",") || []
        }
        list.map(item => {
          let r = dataList?.find(o => o.id === item)
          if (r) result.push(r.sdsName)
        })
      }
      return result?.join("，") || ""
    },
  },
}
</script>

<style scoped lang="scss">
.accidentPreivewNewReport {
  .ty-content {
    padding: 0 20px 80px;
  }
}
</style>
